package com.tang.managementdemo.anno;

import com.tang.managementdemo.mapper.OperateLogMapper;
import com.tang.managementdemo.pojo.OperateLog;
import com.tang.managementdemo.util.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;



@Aspect
@Component
@Slf4j
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, LogOperation log) throws Throwable {
        // 记录方法的执行时间
        long start = System.currentTimeMillis();

        // 获取操作人ID，这里假设通过某种方式获取，例如从SecurityContext中获取
        Integer operateEmpId = getOperateEmpId();

        // 获取操作人Name，这里假设通过某种方式获取，例如从SecurityContext中获取
        String operateEmpName = getOperateEmpName();


        // 记录原始方法
        Object result = joinPoint.proceed();

        // 记录方法执行结束时间
        long end = System.currentTimeMillis();

        // 构建操作日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(operateEmpId);
        operateLog.setOperateEmpName(operateEmpName);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getSignature().getDeclaringTypeName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result == null ? "" : result.toString());
        operateLog.setCostTime((long) (end - start));

        // 保存操作日志
        operateLogMapper.insert(operateLog);

        //7. 清空当前线程绑定的id
        CurrentHolder.remove();

        // 记录方法执行时间
//        log.info("{} cost {} ms", joinPoint.getSignature(), end - start);
        return result;
    }

    private Integer getOperateEmpId() {
        // 这里需要根据实际情况获取操作人ID，例如从SecurityContext中获取
        return CurrentHolder.getCurrentId();

    }
    private String getOperateEmpName() {
        // 这里需要根据实际情况获取操作人ID，例如从SecurityContext中获取
        return CurrentHolder.getCurrentName();

    }
}
